﻿Imports Microsoft.VisualBasic
Imports Aras.IOM
Imports MSXML2
Imports System.Xml
Imports System.IO
Imports System.Net
Imports System.Text





Public Class ConnecteurAras

    Dim conn As HttpServerConnection
    Dim inn As Innovator

    Public Sub New(ByVal url As String, _
                   ByVal db As String, _
                   ByVal InnovUser As String, _
                   ByVal pass As String)



        'pass = Innovator.ScalcMD5(pass)
        conn = IomFactory.CreateHttpServerConnection(url, db, InnovUser, pass)
        Dim login_result As Item = conn.Login


        If login_result.isError Then
            Throw New Exception("login failed")
        End If

        inn = IomFactory.CreateInnovator(conn)

    End Sub


    Public Function addfile(ByVal FileName As String) As String
        Dim result As String = ""

        Dim qryitem As Item = Me.inn.newItem("DossierDocument", "add")
        Dim subitem As Item = Me.inn.newItem("Document", "add")
        subitem.setProperty("FileName", FileName)

        Dim results As Item = qryitem.apply()

        Return result

    End Function


    Public Function UnlockDoc(ByVal ItemId As String) As String

        Dim qryitem As Item = Me.inn.newItem("Document", "unlock")
        qryitem.setAttribute("id", ItemId)
        Dim results As Item = qryitem.apply()
        Dim resultat As String
        If results.isError Then
            resultat = "error"
        Else
            resultat = results.getItemsByXPath("//Result/Item").getID
        End If
        Return resultat
    End Function


    Public Function LockDoc(ByVal ItemId As String) As String

        Dim qryitem As Item = Me.inn.newItem("Document", "lock")
        qryitem.setAttribute("id", ItemId)
        Dim results As Item = qryitem.apply()
        Dim resultat As String
        If results.isError Then
            resultat = "error"
        Else
            resultat = results.getItemsByXPath("//Result/Item").getID
        End If
        Return resultat
    End Function


    Public Function UploadNewDoc(ByVal ItemId As String, _
                                 ByVal filepath As String, _
                                 ByVal filename As String, _
                                 ByVal AddPdf As Boolean, _
                                 ByVal AddThumbnail As Boolean, _
                                 ByVal Pdfordwf As Boolean) As String

        'Document should be locked
        'Upload query
        Dim qryitem As Item = Me.inn.newItem("Document", "update")
        qryitem.setAttribute("id", ItemId)


        'Add Autocad File
        Dim rel As Item = Me.inn.newItem("Document File", "add")
        Dim DocFile As Item = Me.inn.newItem("File", "add")
        DocFile.setProperty("filename", filename)
        DocFile.attachPhysicalFile(filepath)
        qryitem.addRelationship(rel)
        rel.setRelatedItem(DocFile)

        If AddPdf = True Then
            'Add Pdf File
            Dim relNew_PDF = Me.inn.newItem("Document File", "add")
            Dim DocFileNew_PDF = Me.inn.newItem("File", "add")

            '-> création du nom de fichier pdf
            Dim filename_PDF = ""
            Dim filename_PDF_table() As String = filename.Split(".")
            Dim filename_PDF_table_length As Integer = filename_PDF_table.Length
            Dim i As Integer
            For i = 0 To filename_PDF_table_length - 2
                filename_PDF = filename_PDF + filename_PDF_table(i) + "."
            Next

            If Pdfordwf = True Then
                filename_PDF = filename_PDF + "pdf"
            Else
                filename_PDF = filename_PDF + "dwf"
            End If


            DocFileNew_PDF.setProperty("filename", filename_PDF)

            '-> création du chemin de fichier pdf
            Dim filepath_PDF = ""
            Dim filepath_PDF_table() As String = filepath.Split("\")
            Dim filepath_PDF_table_length As Integer = filepath_PDF_table.Length

            For i = 0 To filepath_PDF_table_length - 2
                filepath_PDF = filepath_PDF + filepath_PDF_table(i) + "\"
            Next
            filepath_PDF = filepath_PDF + filename_PDF


            DocFileNew_PDF.attachPhysicalFile(filepath_PDF)
            qryitem.addRelationship(relNew_PDF)
            relNew_PDF.setRelatedItem(DocFileNew_PDF)


           
        End If

            If AddThumbnail = True Then

                'Add Png File


                Dim DocFileNew_PNG = Me.inn.newItem("File", "add")

                '-> création du nom de fichier png
                Dim filename_PDF = ""
                Dim filename_PDF_table() As String = filename.Split(".")
                Dim filename_PDF_table_length As Integer = filename_PDF_table.Length
                Dim i As Integer
                For i = 0 To filename_PDF_table_length - 2
                    filename_PDF = filename_PDF + filename_PDF_table(i) + "."
                Next
                filename_PDF = filename_PDF + "png"
                DocFileNew_PNG.setProperty("filename", filename_PDF)

                '-> création du chemin de fichier png
                Dim filepath_PNG = ""
                Dim filepath_PNG_table() As String = filepath.Split("\")
                Dim filepath_PNG_table_length As Integer = filepath_PNG_table.Length

                For i = 0 To filepath_PNG_table_length - 2
                    filepath_PNG = filepath_PNG + filepath_PNG_table(i) + "\"
                Next
                filepath_PNG = filepath_PNG + filename_PDF

                DocFileNew_PNG.attachPhysicalFile(filepath_PNG)
                Dim AddThumbnailResult As Item
                AddThumbnailResult = DocFileNew_PNG.apply()

                If AddThumbnailResult.isError Then
                    'thumbnail file add failed
                Else
                qryitem.setProperty("thumbnail_item", AddThumbnailResult.getItemsByXPath("//Result/Item").getID)
                End If

            End If


            Dim results As Item = qryitem.apply()
            ' Dim FileID As String = results.getItemsByXPath("//Result/Item").getRelationships.getItemByIndex(0).getRelatedItemID


            Dim resultat As String
            If results.isError Then
                resultat = "error"
            Else
                resultat = "save & upload are done"
            End If

            Me.LockDoc(ItemId)
            MsgBox(resultat)
            Return results.getItemsByXPath("//Result/Item").getID

    End Function

  

    Public Function UploadUpdatedDoc(ByVal ItemId As String, _
                                     ByVal filepath As String, _
                                     ByVal filename As String, _
                                     ByVal AddPdf As Boolean, _
                                     ByVal AddThumbnail As Boolean, _
                                     ByVal Pdfordwf As Boolean) As String


        'Document should be locked
        'upload
        Dim results1 As Item
        Dim qryitem As Item = Me.inn.newItem("Document", "get")
        qryitem.setAttribute("id", ItemId)
        Dim rel As Item = Me.inn.newItem("Document File", "get")
        Dim DocFile As Item = Me.inn.newItem("File", "get")
        qryitem.addRelationship(rel)
        rel.setRelatedItem(DocFile)
        results1 = qryitem.apply()
        Dim FileID As String = results1.getItemsByXPath("//Result/Item").getRelationships.getItemByIndex(0).getRelatedItemID
        Dim DocFileID As String = results1.getItemsByXPath("//Result/Item").getRelationships.getItemByIndex(0).getID

        'test if visualisation file exists
        Dim PdfExists As Boolean = False
        If results1.getItemsByXPath("//Result/Item").getRelationships.getItemCount > 1 Then
            PdfExists = True
        End If

        'test if Thuhmbnail file exists
        Dim PngExists As Boolean = False
        If results1.getItemsByXPath("//Result/Item").getProperty("thumbnail_item") Is Nothing Then
            PngExists = False
        Else
            PngExists = True
        End If


        Dim FileID_PDF As String = ""
        Dim DocFileID_PDF As String = ""
        If PdfExists = True Then
            FileID_PDF = results1.getItemsByXPath("//Result/Item").getRelationships.getItemByIndex(1).getRelatedItemID
            DocFileID_PDF = results1.getItemsByXPath("//Result/Item").getRelationships.getItemByIndex(1).getID
        End If


        'results1 = qryitem.apply()

        qryitem = Me.inn.newItem("Document", "update")
        qryitem.setAttribute("id", ItemId)

        'Delete Autocad File
        Dim relOld = Me.inn.newItem("Document File", "delete")
        relOld.setAttribute("id", DocFileID)
        Dim DocFileOld = Me.inn.newItem("File", "delete")
        DocFileOld.setAttribute("id", FileID)
        relOld.setRelatedItem(DocFileOld)
        qryitem.addRelationship(relOld)

        'Add Autocad File
        Dim relNew = Me.inn.newItem("Document File", "add")
        Dim DocFileNew = Me.inn.newItem("File", "add")
        DocFileNew.setProperty("filename", filename)
        DocFileNew.attachPhysicalFile(filepath)
        qryitem.addRelationship(relNew)
        relNew.setRelatedItem(DocFileNew)

        If AddPdf = True Then

            If PdfExists = True Then

                'Delete PDF File
                Dim relOld_PDF, DocFileOld_PDF As Item
                relOld_PDF = Me.inn.newItem("Document File", "delete")
                relOld_PDF.setAttribute("id", DocFileID_PDF)
                DocFileOld_PDF = Me.inn.newItem("File", "delete")
                DocFileOld_PDF.setAttribute("id", FileID_PDF)
                qryitem.addRelationship(relOld_PDF)
                relOld_PDF.setRelatedItem(DocFileOld_PDF)

            End If

            'Add Pdf File
            Dim relNew_PDF = Me.inn.newItem("Document File", "add")
            Dim DocFileNew_PDF = Me.inn.newItem("File", "add")

            '-> création du nom de fichier pdf
            Dim filename_PDF = ""
            Dim filename_PDF_table() As String = filename.Split(".")
            Dim filename_PDF_table_length As Integer = filename_PDF_table.Length
            Dim i As Integer
            For i = 0 To filename_PDF_table_length - 2
                filename_PDF = filename_PDF + filename_PDF_table(i) + "."
            Next

            If Pdfordwf = True Then
                filename_PDF = filename_PDF + "pdf"
            Else
                filename_PDF = filename_PDF + "dwf"
            End If


            DocFileNew_PDF.setProperty("filename", filename_PDF)

            '-> création du chemin de fichier pdf
            Dim filepath_PDF = ""
            Dim filepath_PDF_table() As String = filepath.Split("\")
            Dim filepath_PDF_table_length As Integer = filepath_PDF_table.Length

            For i = 0 To filepath_PDF_table_length - 2
                filepath_PDF = filepath_PDF + filepath_PDF_table(i) + "\"
            Next
            filepath_PDF = filepath_PDF + filename_PDF


            DocFileNew_PDF.attachPhysicalFile(filepath_PDF)
            qryitem.addRelationship(relNew_PDF)
            relNew_PDF.setRelatedItem(DocFileNew_PDF)



        End If

        If AddThumbnail = True Then



            'Add Png File
            Dim DocFileNew_PNG = Me.inn.newItem("File", "add")

            '-> création du nom de fichier png
            Dim filename_PNG = ""
            Dim filename_PNG_table() As String = filename.Split(".")
            Dim filename_PNG_table_length As Integer = filename_PNG_table.Length
            Dim i As Integer
            For i = 0 To filename_PNG_table_length - 2
                filename_PNG = filename_PNG + filename_PNG_table(i) + "."
            Next
            filename_PNG = filename_PNG + "png"
            DocFileNew_PNG.setProperty("filename", filename_PNG)

            '-> création du chemin de fichier png
            Dim filepath_PNG = ""
            Dim filepath_PNG_table() As String = filepath.Split("\")
            Dim filepath_PNG_table_length As Integer = filepath_PNG_table.Length

            For i = 0 To filepath_PNG_table_length - 2
                filepath_PNG = filepath_PNG + filepath_PNG_table(i) + "\"
            Next
            filepath_PNG = filepath_PNG + filename_PNG

            DocFileNew_PNG.attachPhysicalFile(filepath_PNG)
            Dim AddThumbnailResult As Item
            AddThumbnailResult = DocFileNew_PNG.apply()

            If AddThumbnailResult.isError Then
                'thumbnail file add failed
            Else
                qryitem.setProperty("thumbnail_item", AddThumbnailResult.getItemsByXPath("//Result/Item").getID)
            End If

        End If



        results1 = qryitem.apply()

        Return results1.getItemsByXPath("//Result/Item").getID




    End Function





    Public Function IsDocLocked(ByVal ItemNumber As String) As Integer

        Dim resultat As Integer = 2

        Dim qryitem As Item = Me.inn.newItem("Document", "get")
        qryitem.setAttribute("id", ItemNumber)
        Dim results As Item = qryitem.apply()

        resultat = results.getItemsByXPath("//Result/Item").getLockStatus
        Return resultat

    End Function


    Public Function DocHasFileTest(ByVal ItemId As String) As Boolean
        Dim resultat As Boolean = False

        Dim qryitem As Item = Me.inn.newItem("Document", "get")
        qryitem.setAttribute("id", ItemId)
        Dim rel As Item = Me.inn.newItem("Document File", "get")
        Dim DocFile As Item = Me.inn.newItem("File", "get")
        qryitem.addRelationship(rel)
        rel.setRelatedItem(DocFile)
        Dim results As Item = qryitem.apply()

        If results.getItemsByXPath("//Result/Item").getRelationships.nodeList.Count > 0 Then
            resultat = True
        End If

        Return resultat
    End Function


    Protected Overrides Sub Finalize()
        Try

            conn.Logout()
        Catch ex As Exception
            GoTo fin
        End Try
fin:
        MyBase.Finalize()
    End Sub

    Public Function GetItemListFlagged(ByVal UserName As String) As MSXML2.DOMDocument

        'get the list from Aras
        Dim results As New MSXML2.DOMDocument
        Dim Item_results As Item

        Dim qryitem As Item = Me.inn.newItem("Prodeos_DTO", "get")
        qryitem.setProperty("authoring_tool", "AutoCAD")
        qryitem.setProperty("created_by", UserName)
        Item_results = qryitem.apply()
        results.loadXML(Item_results.ToString)

        Return results

    End Function

    Public Function GetAutocadItemList() As MSXML2.DOMDocument
        'get the list from Aras
        Dim results As New MSXML2.DOMDocument
        Dim Item_results As Item

        Dim qryitem As Item = Me.inn.newItem("Document", "get")
        qryitem.setProperty("authoring_tool", "AutoCAD")
        Item_results = qryitem.apply()
        results.loadXML(Item_results.ToString)

        Return results
    End Function

    Public Function GetAutocadDocProperties() As String()
        Dim PropertyList(50) As String
        Dim Item_results As Item
        Dim documentID As String


        Dim qryitem As Item = Me.inn.newItem("ItemType", "get")
        qryitem.setProperty("name", "Document")
        Item_results = qryitem.apply()
        documentID = Item_results.getItemsByXPath("//Result/Item").getID


        qryitem = Me.inn.newItem("Property", "get")
        qryitem.setProperty("source_id", documentID)
        qryitem.setProperty("is_hidden2", "0")
        Item_results = qryitem.apply()



        Dim NbrElement As Integer = Item_results.getItemsByXPath("//Result/Item").nodeList.Count
        Dim i As Integer
        Dim Nom As String

        For i = 0 To NbrElement - 1
            Nom = Item_results.getItemsByXPath("//Result/Item").nodeList.Item(i).SelectSingleNode("name").InnerText
            PropertyList(i) = Nom

        Next




        Return PropertyList
    End Function


    Public Function GetDocToOpenProperties() As String()
        Dim PropertyList(50) As String
        Dim Item_results As Item
        Dim DTO_ID As String


        Dim qryitem As Item = Me.inn.newItem("ItemType", "get")
        qryitem.setProperty("name", "Prodeos_DTO")
        Item_results = qryitem.apply()
        DTO_ID = Item_results.getItemsByXPath("//Result/Item").getID


        qryitem = Me.inn.newItem("Property", "get")
        qryitem.setProperty("source_id", DTO_ID)
        qryitem.setProperty("is_hidden2", "0")
        Item_results = qryitem.apply()



        Dim NbrElement As Integer
        Try
            NbrElement = Item_results.getItemsByXPath("//Result/Item").nodeList.Count
        Catch ex As Exception
            NbrElement = 1
        End Try
        Dim i As Integer
        Dim Nom As String

        For i = 0 To NbrElement - 1
            Nom = Item_results.getItemsByXPath("//Result/Item").nodeList.Item(i).SelectSingleNode("name").InnerText
            PropertyList(i) = Nom

        Next




        Return PropertyList
    End Function

    Public Sub DeleteDTOitem(ByVal ID As String)

        Dim Item_results As Item
        Dim qryitem As Item = Me.inn.newItem("Prodeos_DTO", "delete")
        qryitem.setAttribute("id", ID)
        Item_results = qryitem.apply()
        If Item_results.isError Then
            MsgBox("Error while deleting the selected Item")
        End If

    End Sub

    Public Function getLocalWorkFolder(ByVal username As String) As String
        Dim FolderPath As String
        Dim Item_results As Item
        Dim qryitem As Item = Me.inn.newItem("user", "get")
        qryitem.setProperty("login_name", username)
        Item_results = qryitem.apply()
        Try
            FolderPath = Item_results.getItemsByXPath("//Result/Item").getProperty("working_directory")
        Catch ex As Exception
            FolderPath = ""
            MsgBox("Error while looking for the local work folder")
        End Try

        Return FolderPath
    End Function

    Public Function GetFileName(ByVal DTO_ID As String, _
                                ByVal row As Integer) As String()

        Dim DocumentID As String
        Dim FileInfo(2) As String

        Dim qryitem, Item_results, RelItem, FileItem As Item
        qryitem = Me.inn.newItem("Prodeos_DTO", "get")
        qryitem.setAttribute("id", DTO_ID)
        Item_results = qryitem.apply()
        DocumentID = Item_results.getItemsByXPath("//Result/Item").getProperty("docid")

        qryitem = Me.inn.newItem("Document", "get")
        qryitem.setAttribute("id", DocumentID)
        RelItem = Me.inn.newItem("Document File", "get")
        FileItem = Me.inn.newItem("File", "get")
        RelItem.setRelatedItem(FileItem)
        qryitem.addRelationship(RelItem)
        Item_results = qryitem.apply()



        Try


            FileInfo(0) = Item_results.getItemsByXPath("//Result/Item/Relationships/Item[1]/related_id/Item").getProperty("filename")
            FileInfo(1) = Item_results.getItemsByXPath("//Result/Item/Relationships/Item[1]/related_id/Item").getProperty("checksum")
            FileInfo(2) = Item_results.getItemsByXPath("//Result/Item/Relationships/Item[1]/related_id/Item").getProperty("file_size")


        Catch ex As Exception
            MsgBox("The Document on line " & row & " has not been Created")
        End Try
        Return FileInfo
    End Function

    Public Function CheckOutDocFile(ByVal DocumentFileID As String, _
                                    ByVal WorkingDir As String, _
                                    ByVal DocType As String(), _
                                    ByVal ARASURL As String, _
                                    ByVal ARASDB As String) As String

        Dim CheckOutProcess, FileTypeID, FileID, FileName, DownloadFilepath As String
        Dim qryitem, Item_results, RelItem, FileItem As Item
        Dim DownloadBool As Boolean = False


        FileID = ""
        FileName = ""
        DownloadFilepath = ""
        CheckOutProcess = ""

        'Get FileType ID based on DocType
        qryitem = Me.inn.newItem("FileType", "get")
        qryitem.setProperty("name", DocType(0))
        qryitem.setProperty("extension", DocType(1))
        Item_results = qryitem.apply()
        FileTypeID = Item_results.getItemsByXPath("//Result/Item").getID


        'CheckOut the File corresponding to the Doctype
        qryitem = Me.inn.newItem("Document", "get")
        qryitem.setAttribute("id", DocumentFileID)
        RelItem = Me.inn.newItem("Document File", "get")
        FileItem = Me.inn.newItem("File", "get")
        FileItem.setProperty("file_type", FileTypeID)
        RelItem.setRelatedItem(FileItem)
        qryitem.addRelationship(RelItem)
        Item_results = qryitem.apply()


        Try
            FileID = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").getID
            Item_results = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").checkout(WorkingDir)
            FileName = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").getProperty("filename")
            DownloadFilepath = ARASURL & "/vault/vaultserver.aspx?dbName=" & ARASDB & "&fileID=" & FileID & "&fileName=" & FileName
            DownloadBool = Me.downloadvaultedfile(DownloadFilepath, WorkingDir & "\" & FileName)
            CheckOutProcess = "Ok"
        Catch ex As Exception
            MsgBox(ex.Message)
            CheckOutProcess = "Error"
        End Try




        Return CheckOutProcess
    End Function

    Public Sub CreateDTOfromItemNbr(ByVal item_number As String)

        Dim qryitem, RelItem, FileItem As Item
        Dim Item_results As Item
        Dim DOCID, CLASSE, STATUT_DTO, AUTHORING, DOCNAME, FileTypeID As String
        Dim DocType(1) As String

        DocType(0) = "AUTOCAD"
        DocType(1) = "dwg"

        'Get FileType ID based on DocType
        qryitem = Me.inn.newItem("FileType", "get")
        qryitem.setProperty("name", DocType(0))
        qryitem.setProperty("extension", DocType(1))
        Item_results = qryitem.apply()
        FileTypeID = Item_results.getItemsByXPath("//Result/Item").getID

        qryitem = Me.inn.newItem("Document", "get")
        qryitem.setProperty("item_number", item_number)
        RelItem = Me.inn.newItem("Document File", "get")
        FileItem = Me.inn.newItem("File", "get")
        FileItem.setProperty("file_type", FileTypeID)
        RelItem.setRelatedItem(FileItem)
        qryitem.addRelationship(RelItem)
        Item_results = qryitem.apply()
        Try



            DOCID = Item_results.getItemsByXPath("//Result/Item").getID

            CLASSE = Item_results.getItemsByXPath("//Result/Item").getProperty("classification")
            STATUT_DTO = "modify"
            AUTHORING = "AutoCAD"
            DOCNAME = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").getProperty("filename")


            qryitem = Me.inn.newItem("Prodeos_DTO", "add")
            qryitem.setProperty("docid", DOCID)
            qryitem.setProperty("classe", CLASSE)
            qryitem.setProperty("statut_dto", STATUT_DTO)
            qryitem.setProperty("authoring_tool", AUTHORING)
            qryitem.setProperty("documentname", DOCNAME)
            Item_results = qryitem.apply()
            If Item_results.isError Then
                MsgBox("Error while adding the selected Item")
            End If
        Catch ex As Exception
            MsgBox("First Time creation as to be launched from Aras")
        End Try
    End Sub

    Public Function DownloadTemplate(ByVal Classe As String, _
                                     ByVal WorkingDir As String) As String

        Dim filename, CheckOutProcess As String
        Dim qryitem, Item_results, RelItem, FileItem As Item
        filename = ""
        qryitem = Me.inn.newItem("Prodeos_OC_Templates", "get")
        qryitem.setProperty("docclasspath", Classe)
        RelItem = Me.inn.newItem("TemplateFile", "get")
        FileItem = Me.inn.newItem("File", "get")
        RelItem.setRelatedItem(FileItem)
        qryitem.addRelationship(RelItem)
        Item_results = qryitem.apply()
        Try
            Item_results = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").checkout(WorkingDir)
            filename = Item_results.getItemsByXPath("//Result/Item/Relationships/Item/related_id/Item").getProperty("filename")

            If Item_results.isError Then
                CheckOutProcess = Item_results.getErrorString
            Else
                CheckOutProcess = "OK"
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            CheckOutProcess = "OK"
        End Try

        Return filename
    End Function

    Private Function downloadvaultedfile(ByVal fileadddress As String, _
                                         ByVal filedestination As String) As Boolean

        Dim wc As New System.Net.WebClient
        wc.DownloadFile(fileadddress, filedestination)

    End Function
End Class
